<?php
/**
 * Created by lzl
 * Date: 2021 2021/9/28
 * Time: 10:51
 */
namespace App\Plugins\Forms;

use App\Models\Plugin;
use App\Models\ShareFreeGood;
use App\Models\ShareFreeLog;
use App\Models\ShareFreeOrder;
use Illuminate\Database\Query\Builder;

class ShareFreeForms extends BaseForms
{

    /**
     * @param $validated
     * @return mixed
     */
    public function getShareGoodsList($validated = [])
    {
        $list = ShareFreeGood::where(function ($q) use ($validated){
            /**
             * @var Builder $q
             */
//            if(isset($validated['page']) && isset($validated['limit'])){
//                $q->page($validated['page'], $validated['limit']);
//            }
//
            return $q;

        })->page(function ($q) use ($validated){
            /**
             * @var Builder $q
             */
            if(isset($validated['page']) && isset($validated['limit'])){
                $q->page($validated['page'], $validated['limit']);
            }

        })->orderBy('sort','desc')
            ->get();
        return $list;
    }


    /**
     * @param $validated
     * @return mixed
     */
    public function getShareOrderList($validated)
    {
        $list = ShareFreeOrder::where([])
            ->page($validated['page'], $validated['limit'])
            ->orderBy('id','desc')
            ->get();
        return $list;
    }


    /**
     * @param $validated
     * @param $order_id
     * @return mixed
     */
    public function getShareOrderLogList($validated, $order_id)
    {
        $list = ShareFreeLog::where('order_id', $order_id)
            ->page($validated['page'], $validated['limit'])
            ->orderBy('id','desc')
            ->get();
        return $list;
    }


    /**
     * @return array
     */
    public function getPlugin()
    {
        return [
            'plugin'      => Plugin::where('code', 'share_free')->first(),
            'order_count' => ShareFreeOrder::count(),
        ];
    }


    /**
     * @param $validated
     * @return ShareFreeGood|\Illuminate\Database\Eloquent\Model
     */
    public function getGoodsOrNew($validated)
    {
        return ShareFreeGood::firstOrNew(['id' => $validated['id'] ?? 0]);
    }


    /**
     * @param $validated
     * @return ShareFreeGood|\Illuminate\Database\Eloquent\Model
     */
    public function editShareGoods($validated)
    {
        return ShareFreeGood::updateOrCreate(['id' => $validated['id'] ?: 0], $validated);
    }


    /**
     * @param $id
     * @return int
     */
    public function destroy($id)
    {
        return ShareFreeGood::destroy($id);
    }


}